import { updateQuestionBankUsingPost } from "@/api/questionBankController";
import { ProColumns, ProTable } from "@ant-design/pro-components";
import { message, Modal, Upload } from "antd";
import React, { useState, useEffect } from "react";
import { PlusOutlined } from "@ant-design/icons";
import type { UploadFile, RcFile, UploadProps } from "antd/es/upload/interface";
import { uploadFileUsingPost } from "@/api/fileController";

interface Props {
  oldData?: API.QuestionBank;
  visible: boolean;
  columns: ProColumns<API.QuestionBank>[];
  onSubmit: (values: API.QuestionBankUpdateRequest) => void;
  onCancel: () => void;
}

/**
 * 更新节点
 * @param fields 题库信息
 */
const handleUpdate = async (fields: API.QuestionBankUpdateRequest) => {
  const hide = message.loading("正在更新");
  try {
    await updateQuestionBankUsingPost(fields);
    hide();
    message.success("更新成功");
    return true;
  } catch (error: any) {
    hide();
    message.error("更新失败，" + error.message);
    return false;
  }
};

/**
 * 更新弹窗
 * @param props
 * @constructor
 */
const UpdateModal: React.FC<Props> = (props) => {
  const { oldData, visible, columns, onSubmit, onCancel } = props;
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [imageUrl, setImageUrl] = useState<string>();
  const [uploading, setUploading] = useState(false);

  // 初始化已有图片
  useEffect(() => {
    if (oldData?.picture) {
      setImageUrl(oldData.picture);
      setFileList([
        {
          uid: "-1",
          name: "cover.png",
          status: "done",
          url: oldData.picture,
        },
      ]);
    }
  }, [oldData]);

  /**
   * 自定义上传实现
   */
  const customRequest: UploadProps["customRequest"] = async ({
    file,
    onSuccess,
    onError,
  }) => {
    const hide = message.loading("正在上传图片...");
    setUploading(true);

    try {
      const res = await uploadFileUsingPost(
        { biz: "user_avatar" },
        {},
        file as File,
      );
      const url = res.data;
      if (!url) throw new Error("获取图片URL失败");
      setImageUrl(url);
      onSuccess?.(res.data);
      message.success("图片上传成功");
    } catch (error: any) {
      message.error("上传失败: " + error.message);
      onError?.(error);
    } finally {
      hide();
      setUploading(false);
    }
  };

  /**
   * 上传前校验
   */
  const beforeUpload = (file: RcFile) => {
    const isImage = file.type.startsWith("image/");
    if (!isImage) {
      message.error("只能上传图片文件!");
      return Upload.LIST_IGNORE;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片大小不能超过2MB!");
      return Upload.LIST_IGNORE;
    }
    return true;
  };

  /**
   * 处理文件变化
   */
  const handleChange: UploadProps["onChange"] = ({ file }) => {
    if (file.status === "removed") {
      setImageUrl(undefined);
      setFileList([]);
    } else {
      setFileList([file]);
    }
  };

  /**
   * 修改columns配置，将图片字段改为上传组件
   */
  const modifiedColumns = columns.map((column) => {
    if (column.dataIndex === "picture") {
      return {
        ...column,
        renderFormItem: () => (
          <Upload
            name="picture"
            listType="picture-card"
            fileList={fileList}
            customRequest={customRequest}
            beforeUpload={beforeUpload}
            onChange={handleChange}
            maxCount={1}
            disabled={uploading}
            onPreview={() => window.open(imageUrl)}
          >
            {imageUrl ? (
              <img
                src={imageUrl}
                alt="cover"
                style={{
                  width: "100%",
                  height: "100%",
                  objectFit: "cover",
                }}
              />
            ) : (
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>更换封面</div>
              </div>
            )}
          </Upload>
        ),
      };
    }
    return column;
  });

  if (!oldData) {
    return <></>;
  }

  return (
    <Modal
      destroyOnClose
      title="更新题库"
      open={visible}
      footer={null}
      onCancel={() => {
        setFileList([]);
        setImageUrl(oldData?.picture); // 重置为原始图片
        onCancel?.();
      }}
      width={800}
    >
      <ProTable
        type="form"
        columns={modifiedColumns}
        form={{
          initialValues: oldData,
          preserve: false,
        }}
        onSubmit={async (values: API.QuestionBankUpdateRequest) => {
          // 使用现有图片或新上传的图片
          const finalPicture = imageUrl || oldData?.picture;

          if (!finalPicture) {
            message.warning("请上传封面图片");
            return;
          }
          if (!values.title?.trim()) {
            message.error("请输入标题");
            return;
          }
          if (!values.description?.trim()) {
            message.error("请输入描述");
            return;
          }

          const submitValues = {
            ...values,
            id: oldData.id,
            picture: finalPicture,
          };

          const success = await handleUpdate(submitValues);
          if (success) {
            onSubmit?.(submitValues);
            // 保留当前图片状态
            setFileList([
              {
                uid: "-1",
                name: "cover.png",
                status: "done",
                url: finalPicture,
              },
            ]);
          }
        }}
        rowKey="id"
      />
    </Modal>
  );
};

export default UpdateModal;
